
/*
* 打成一个压缩包
* @metas_zip是一个object key是文件名  value是文件内容
* @filename是压缩包的名字
* */
function metas_save_zip(metas_zip,filename){

    var zip = new JSZip();
    for(var i in metas_zip){
        zip.file(i,metas_zip[i])
    }

    zip.generateAsync({type:"blob"}).then(function(content) {
        // Force down of the Zip file
        saveAs(content, filename);
    });
}

/**
 * Save blocks to local file.
 * better include Blob and FileSaver for browser compatibility
 */
function save() {
    var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var data = Blockly.Xml.domToText(xml);
//  var fileName = window.prompt('是否保存工程文件，文件名?', 'BlocklyDuino');
    var metas_zip=new Object();
    metas_zip["blocks.xml"]=data;
    var zip_filename="MRC.mt";
    metas_save_zip(metas_zip,zip_filename);

}

/**
 * Load blocks from local file.
 */
function load(event) {
    var block_xml = "";
    var new_zip = new JSZip();
    var project_name=this.files[0]
    new_zip.loadAsync(this.files[0]).then(function (zip) {
        new_zip.file("blocks.xml").async("string")
            .then(function (content) {
                    // use content
                    block_xml = content;
                    if(block_xml!=""){
                        try {
                            var xml = Blockly.Xml.textToDom(block_xml);
                        } catch (e) {
                            show_mrc_tip(gettext('Error loading project file, block file error'));
                            return;
                        }
                        var count = Blockly.mainWorkspace.getAllBlocks().length;
                        Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
                        project_name=project_name.name.split(".")[0];
                        $("#project_name").text(project_name);
                        $("#project_name").css("display","block");
                    }

                }
            );
    });
}


/*新建一个空的工程，初始blocks和人物 背景*/
function new_empty_project() {
    var empty_figure_active='{"backgrounds":[],"humans":["./img/human/753c35deaf4b507f.png","./img/human/5f1decb5302f330b.png"],"currentBg":"","currentHm":"./img/human/753c35deaf4b507f.png"}';
    if(confirm(gettext('Do you empty the current project and create a new empty project?'))){
        Blockly.mainWorkspace.clear();
        $("#project_name").text('');
        $("#project_name").css("display","none");
        initByConfig(empty_figure_active,true);
        ActionBlock.isAction();
        ActionBlock.reset();
    }
}

/**
 * Discard all blocks from the workspace.
 */
function discard() {
    var count = Blockly.mainWorkspace.getAllBlocks().length;
    if(confirm(gettext('Confirm clear edited building blocks'))) {
        if (count < 2 || window.confirm('Delete all ' + count + ' blocks?')) {
            Blockly.mainWorkspace.clear();
            renderContent();
        }
    }
}


var opts = {
    lines: 13, // 花瓣数目
    length: 20, // 花瓣长度
    width: 10, // 花瓣宽度
    radius: 30, // 花瓣距中心半径
    corners: 1, // 花瓣圆滑度 (0-1)
    rotate: 0, // 花瓣旋转角度
    direction: 1, // 花瓣旋转方向 1: 顺时针, -1: 逆时针
    color: '#000', // 花瓣颜色
    speed: 1, // 花瓣旋转速度
    trail: 60, // 花瓣旋转时的拖影(百分比)
    shadow: false, // 花瓣是否显示阴影
    hwaccel: false, //spinner 是否启用硬件加速及高速旋转
    className: 'spinner', // spinner css 样式名称
    zIndex: 2e9, // spinner的z轴 (默认是2000000000)
    top: 'auto', // spinner 相对父容器Top定位 单位 px
    left: 'auto'// spinner 相对父容器Left定位 单位 px
};

var spinner = new Spinner(opts);


function uploadClick() {
    var code = Blockly.Arduino.workspaceToCode();
    upload_online_run_xml(1,code,0);
    var mcu="";
    var i_ele=$("li.board").find("i");
    for(var i=0;i<i_ele.length;i++){
        var style=$(i_ele[i]).attr("style");
        if(style.indexOf("block")>=0){
            mcu=$(i_ele[i]).siblings("a").attr("value");
            break;
        }
    }

    var new_code={"arduino_code":code,"mcu":mcu};


    if(confirm(gettext('Make sure to burn the code to MRC.'))) {
        // var result=uploadCode(new_code);
        $("#load_wait").text(gettext("Uploading code, please wait")+"。。。。。。");
        var target = $("#load_wait").get(0);
        spinner.spin(target);
        $.ajax({
            url: "http://localhost:8089/burn/",
            type: "POST",
            data:JSON.stringify(new_code),
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#load_wait").text("");
                spinner.spin();
                if(XMLHttpRequest.readyState==0){
                    var message=gettext('MRC Assistant is not turned on!');
                }
                else{
                    var message=gettext('MRC assistant internal error!');
                }
                show_mrc_tip(message)
            },
            success: function (data) {
                var state=data['state'];
                var message=data['message'];
                $("#load_wait").text("");
                spinner.spin();
                show_mrc_tip(message,true)
            }
        });
    }
}

function resetClick() {
    var code = "void setup() {} void loop() {}";


    upload_online_run_xml(0,code,0);
    var mcu="";
    var i_ele=$("li.board").find("i");
    for(var i=0;i<i_ele.length;i++){
        var style=$(i_ele[i]).attr("style");
        if(style.indexOf("block")>=0){
            mcu=$(i_ele[i]).siblings("a").attr("value");
            break;
        }
    }
    var new_code={"arduino_code":code,"mcu":mcu};

    if(confirm(gettext('Confirm reset MRC board.'))) {
        // var result=uploadCode(new_code);
        // alert(result.message);
        $("#load_wait").text(gettext("Uploading code, please wait")+"。。。。。。");
        var target = $("#load_wait").get(0);
        spinner.spin(target);
        $.ajax({
            url: "http://localhost:8089/burn/",
            type: "POST",
            data:JSON.stringify(new_code),
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#load_wait").text("");
                spinner.spin();
                if(XMLHttpRequest.readyState==0){
                    var message=gettext('MRC Assistant is not turned on!');
                }
                else{
                    var message=gettext('MRC assistant internal error!');
                }
                show_mrc_tip(message)
            },
            success: function (data) {
                var state=data['state'];
                var message=data['message'];
                $("#load_wait").text("");
                spinner.spin();
                show_mrc_tip(message,true)
            }
        });
    }
}


function upload_online_run_xml(user_edit,arduino_code,mode) {
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    var json_data=new Object();
    json_data["arduino_code"]=arduino_code;
    json_data["xml"]=xmlText;
    json_data["block_count"]=workspace.getAllBlocks().length;
    json_data["user_edit"]=user_edit;
    json_data['mode']=mode
    var new_code=JSON.stringify(json_data);
    $.ajax({
        url: "http://"+window.location.host+"/mrc/upload_online_run_xml/",
        type: "Post",
        data:new_code,
        dataType: "json",
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function (data) {
        }
    });
}

$(document).ready(function () {
    window.board_name="MRC";
    $('.character_start').mouseover(function (ele) {
        var image=$('.character_start').find('img');
        var src=$(image).attr('src');
        if(src!='/static/img/run_blockly_bright.png'){
            $(image).attr('src','/static/img/run_blockly_bright.png');
        }

    });
    $('.character_start').mouseleave(function (ele) {
        var image=$('.character_start').find('img');
        var src=$(image).attr('src');
        var blockly_is_run=window.blockly_is_run;
        if(blockly_is_run==false || blockly_is_run==null){
            if(src!='/static/img/run_blockly_dark.png'){
                $(image).attr('src','/static/img/run_blockly_dark.png');
            }
        }
    });
    $('#character_reset').mouseover(function (ele) {
        var image=$('#character_reset').find('img');
        var src=$(image).attr('src');
        if(src!='/static/img/stop_blockly_bright.png'){
            $(image).attr('src','/static/img/stop_blockly_bright.png');
        }

    });
    $('#character_reset').mouseleave(function (ele) {
        var image=$('#character_reset').find('img');
        var src=$(image).attr('src');
        if(src!='/static/img/stop_blockly_dark.png'){
            $(image).attr('src','/static/img/stop_blockly_dark.png');
        }
    });
    var match = location.search.match(/toolbox=([^&=\/]+)/);
    var toolbox = match ? match[1] : 'simple';
    $.ajax({
        url: "http://localhost:8089/mode_state/",
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#blockly_mode').text(gettext('Burn mode'));
            $('.character_start').css('pointer-events', 'none');
            $('.character_start').find('img').attr('src', '/static/img/run_blockly_none.png');
            $('#character_reset').css('pointer-events', 'none');
            $('#character_reset').find('img').attr('src', '/static/img/stop_blockly_none.png');
            window.mrc_mode_state=0;
        },
        success: function (data) {
            var state=data["state"];
            var message=data["message"];
            var mode=data["mode"];
            if (state!=0){
                show_mrc_tip(message);
            }
            else{
                if(mode=='0'){
                    if(toolbox!="simple"){

                        location.href='/mrc/index/?toolbox=simple';
                    }else {
                        $('#blockly_mode').text(gettext('Burn mode'));
                        $('.character_start').css('pointer-events', 'none');
                        $('.character_start').find('img').attr('src', '/static/img/run_blockly_none.png');
                        $('#character_reset').css('pointer-events', 'none');
                        $('#character_reset').find('img').attr('src', '/static/img/stop_blockly_none.png');

                        window.online_data_obj.set_start_state(false);
                        window.mrc_mode_state=0;
                    }
                }else{
                    if(toolbox!="js_simple"){
                        location.href='/mrc/index/?toolbox=js_simple';
                    }else{
                        $('#blockly_mode').text(gettext('Firmata mode'));
                        $('#arduino_upload_sketch').css('pointer-events','none');
                        $('#arduino_upload_sketch').css('color','#999');
                        $('#arduino_reset_sketch').css('pointer-events','none');
                        $('#arduino_reset_sketch').css('color','#999');

                        window.online_data_obj.set_start_state(true);
                        window.mrc_mode_state=1;
                    }

                }
            }

        }
    });

  window.setInterval(function () {
    check_connect_state();
  },1000);
  $('#show_history').mouseover(function (ele) {
        refresh_history();
    });


$('.historyyes').click(function (e) {
    var history_id=$('.historyyes').parent().parent().children('p').children('span').attr("xml_id");
    $.ajax({
        url: "http://"+window.location.host+"/mrc/get_xml_history/?xml_id="+history_id,
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          show_mrc_tip("error!" + errorThrown);

        },
        success: function (data) {
          var code=data['code'];
          var block_xml=data['xml_data'];
          var msg=data['msg'];
          if(code==1){
            show_mrc_tip(msg)
          }
          else{
            if(block_xml!=""){
                     try {
                    var xml = Blockly.Xml.textToDom(block_xml);
                } catch (e) {
                    show_mrc_tip(gettext('Error loading project file, block file error'));
                    return;
                }
                var count = Blockly.mainWorkspace.getAllBlocks().length;
                Blockly.mainWorkspace.clear();
                Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
                $("#project_name").css("display","none");
                }
          }
        }
      });

  });

  $('.deletehistoryyes').click(function(){
    var history_id=$('.deletehistoryyes').parent().parent().children('p').children('span').attr("xml_id");
    var li_list=$('.history li');
    for(var i=0;i<li_list.length;i++){
      var li=li_list[i];
      var xml_id=$(li).children('a').attr("xml_id");
      if(history_id==xml_id){
        $.ajax({
        url: "http://"+window.location.host+"/mrc/delete_xml_history/?xml_id="+history_id,
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          show_mrc_tip("error!" + errorThrown);

        },
        success: function (data) {
           var code=data['code'];
          var msg=data['msg'];
          if(code==1){
            show_mrc_tip(msg)
          }
          else {
             li.remove();
          }
        }
      });
      }
    }
});


});



function check_connect_state(){

    $.ajax({
        url: "http://localhost:8089/connect_state/",
        type: "Get",
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          if($(".connect_state").attr("title")!=gettext('Not connected to MRC')){
              $(".connect_state").attr("src","/static/img/hong.png");
              $(".connect_state").attr("title",gettext('Not connected to MRC'));
            }
        },
        success: function (data) {
            var state=data['state'];
            if(state=="1"){
                if($(".connect_state").attr("title")!=gettext('Successfully connected to MRC')){
                  $(".connect_state").attr("src","/static/img/lv.png");
                  $(".connect_state").attr("title",gettext('Successfully connected to MRC'))
                }
              }
              else{
                if($(".connect_state").attr("title")!=gettext('Not connected to MRC')){
                  $(".connect_state").attr("src","/static/img/hong.png");
                  $(".connect_state").attr("title",gettext('Not connected to MRC'));
                }
              }
        }
      });

}



function refresh_history() {
  //获取用户积木编辑历史记录
  var history=$('.history');
  history.html('');
  $.ajax({
        url: "http://"+window.location.host+"/mrc/get_history_list/",
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {

        },
        success: function (data) {
          for(var i=0;i<data.length;i++){
            var li='<li> <a href="#" data-toggle="modal" data-target="#myModal03" xml_id="'+data[i][0]+'">'+data[i][1]+'</a><button data-toggle="modal" data-target="#myModal04" class="delete_his" his_name="'+data[i][1]+'"xml_id="'+data[i][0]+'">'+gettext('remove')+'</button></li>';
            history.append(li);
            $('.history li a').click(function(){
                var fonts=$(this).html();
                var xml_id=$(this).attr("xml_id");
                var fontss="<span xml_id='"+xml_id+"'>"+fonts+"</span>";
                $('.hisp span').replaceWith(fontss);
                $('.deletehisp span').replaceWith(fontss);
            });

            $('.history li button').click(function(){
                var fonts=$(this).attr('his_name');
                var xml_id=$(this).attr("xml_id");
                var fontss="<span xml_id='"+xml_id+"'>"+fonts+"</span>";
                $('.deletehisp span').replaceWith(fontss);
            });
          }
          if(data.length==0){
            var li='<li> <a href="#" data-toggle="modal" data-target="#">'+gettext('No history')+'</a>';
            history.append(li);
          }

        }
      });
}

function select_board(el) {
    var board = el.getAttribute("value");
    var board_name=$(el).text();
    var parent_el = $(el).parent("li");
    var ul_parent_el = $(el).parent("li").parent("ul");

    ul_parent_el.find("i").css("display", "none");
    parent_el.find("i").css("display", "block");
    window.board_name=board_name;
    show_mrc_tip(gettext('Selection board succeeded'),true);


  }

$(document).ready(function () {
    $('#project_examples').empty();
    var file_list=[];
    $.ajax({
        url: "/mrc/get_example_list/",
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert("error!" + errorThrown);
        },
        success: function (data) {
            // var parse_data=JSON.parse(data);
            file_list=data;
        }
    });
    for(var i=0;i<file_list.length;i++){
        var one_example='<li><a href="javascript:void(0)" onclick="get_example_project(this)">'+file_list[i]+'</a></li>';
        $('#project_examples').append(one_example);
    }
});

/* 加载工程样例*/
function get_example_project(ele) {
    var file_data=null;
    var file_name=$(ele).text();
    $.ajax({
        url: "/mrc/get_example_project/?name="+file_name,
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert("error!" + errorThrown);

        },
        success: function (data) {
            file_data=data;
        }
    });
    var block_xml = file_data['blocks.xml'];
    var project_name=file_data['project_name'];
    if(block_xml!=""){
        try {
            var xml = Blockly.Xml.textToDom(block_xml);
        } catch (e) {
            return;
        }
        var count = Blockly.mainWorkspace.getAllBlocks().length;
        Blockly.mainWorkspace.clear();
        Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
        $("#project_name").text(project_name);
        $("#project_name").css("display","block");
    }
}



$(document).ready(function () {
    $('#show_cloud_projects').on('show.bs.modal',function (ele) {
        $('#show_cloud_projects .modal-body table').hide();
        $('#show_cloud_projects .modal-body img').css('display','block');
        $.ajax({
            url: "/mrc/get_cloud_project_list/",
            type: "Get",
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // alert("error!" + errorThrown);

            },
            success: function (data) {
                var data_list=data['data'];
                var all_li="";
                for(var i=0;i<data_list.length;i++){
                    var on_li='<tr>\n' +
                        '<td author="'+data_list[i]['author']+'" project_id="'+data_list[i]['id']+'">'+data_list[i]['id']+'</td>\n' +
                        '<td ><a class="cloud_change_name" data-type="text" title="'+gettext('点击修改工程名字')+'" data-pk="'+data_list[i]['id']+'" data-name="'+data_list[i]['author']+'">'+data_list[i]['title']+'</a></td>\n' +
                        '<td>'+data_list[i]["update"]+'</td>\n' +
                        '<td>\n' +
                        '<button type="button" class="btn btn-primary btn-xs cloud_project_open">'+gettext('打开')+'</button>\n' +
                        '<button type="button" class="btn btn-primary btn-xs cloud_project_delete">'+gettext('删除')+'</button>\n' +
                        '</td>\n' +
                        '</tr>';
                    all_li+=on_li;
                }
                if(all_li==""){
                    var on_li='<tr><td colspan="4" align="center">'+gettext('无云工程保存记录')+'</td></tr>';
                    all_li+=on_li;
                }
                $('#show_cloud_projects .modal-body img').css('display','none');
                $('#show_cloud_projects .modal-body table').show();
                $('#show_cloud_projects .modal-body table tbody').html(all_li);
                $('.cloud_change_name').editable({
                    mode: "inline",
                    validate: function (value) { //字段验证
                        if (!$.trim(value)) {
                            return gettext('不能为空');
                        }
                    },
                    url: function (params) {
                        cloud_change_name_func(params.pk,params.name,params.value)
                    }
                })
            }
        });
    });
    function cloud_change_name_func(id,user_id,name) {
        var new_code=JSON.stringify({"id":id,"user_id":user_id,"name":name});
        $.ajax({
            url: "/mrc/change_cloud_project_name/",
            type: "Post",
            data:new_code,
            dataType: "json",
            beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);

                },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // alert("error!" + errorThrown);

            },
            success: function (data) {
            }
        });
    }

});

$(document).on('click','.cloud_project_open',function () {
    var first_td=$(this).parents('tr').find('td:first');
    var project_id=$(first_td).attr('project_id');
    var new_code=JSON.stringify({"id":project_id});
    $.ajax({
        url: "/mrc/get_cloud_project_data/",
        type: "Post",
        data:new_code,
        dataType: "json",
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert("error!" + errorThrown);

        },
        success: function (data) {
            var code=data['code'];
            if(code!=0){
                var msg=data['msg'];
                // alert(msg);
                show_mrc_tip(msg,false)
            }else{
                var block_xml=data["data"]['xml_content'];
                var project_name=data['data']['title'];

                if(block_xml!=""){
                    try {
                        var xml = Blockly.Xml.textToDom(block_xml);
                    } catch (e) {
                        show_mrc_tip(gettext('Error loading project file, block file error'));
                        return;
                    }
                    var count = Blockly.mainWorkspace.getAllBlocks().length;
                    Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
                    $("#project_name").text(project_name);
                    $("#project_name").css("display","block");

                    $('#show_cloud_projects').modal('hide');
                }
            }

        }
    });
});

$(document).on('click','.cloud_project_delete',function () {
    var tr_ele=$(this).parents('tr');
    var first_td=$(this).parents('tr').find('td:first');
    var project_id=$(first_td).attr('project_id');
    var new_code=JSON.stringify({"id":project_id});
    $.ajax({
        url: "/mrc/delete_cloud_project_data/",
        type: "Post",
        data:new_code,
        dataType: "json",
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert("error!" + errorThrown);

        },
        success: function (data) {
            var code=data['code'];
            if(code!=0){
                var msg=data['msg'];
                show_mrc_tip(msg);
            }else{
                $(tr_ele).remove();
            }

        }
    });
});


function save_project_to_cloud(ele) {
        var project_name=prompt(gettext("请输入需要保存到云端的工程名"));
        if(project_name=='' || project_name==null){
            show_mrc_tip(gettext('保存失败，请不要输入一个空的工程名字'));
            return
        }
        var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
        var data = Blockly.Xml.domToText(xml);
        var new_code=JSON.stringify({'xml':data,'title':project_name});
        $.ajax({
        url: "/mrc/save_cloud_project_data/",
        type: "Post",
        data:new_code,
        dataType: "json",
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert("error!" + errorThrown);

        },
        success: function (data) {
            var code=data['code'];
            var msg=data['msg'];
            if(code!=0){
                show_mrc_tip(msg);
            }else{
                show_mrc_tip(msg,true);
            }

        }
    });
}
